<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sfexpress extends Backend {

	public function __construct()
	{
		parent::__construct();
        $this->load->model(['category_model','goods_model','sf_model','siteorder_model','site_model']);
		$this->data['page_home']  = lang('lang_dashboard');
		$this->data['page_title'] = '顺丰物流';
	}


	public function index($orderid=0)
	{
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			$this->data['page_title'] => 'backend/sfexpress'
		);

      
        $config = $this->systemconfig_model->get_configs(); 


        $this->form_validation->set_rules('enname', '申报英文名', 'required');
        $this->form_validation->set_rules('cnname', '申报中文名', 'required');
        $this->form_validation->set_rules('number', '申报数量', 'required');
        $this->form_validation->set_rules('price', '申报单价', 'required');
        $this->form_validation->set_rules('total', '申报总价', 'required');
        $this->form_validation->set_rules('re_state', '收件人省/洲', 'required');
        $this->form_validation->set_rules('re_city', '收件人城市', 'required');
        $this->form_validation->set_rules('re_postcode', '收件人邮编', 'required');
        $this->form_validation->set_rules('re_address', '收件人地址', 'required');
        $this->form_validation->set_rules('re_mobile', '收件人手机', 'required');
        $this->form_validation->set_rules('re_phone', '收件人电话', 'required');
        $this->form_validation->set_rules('reciver', '收件人姓名', 'required');

        $this->form_validation->set_rules('se_company', '寄件人公司', 'required');
        $this->form_validation->set_rules('sender', '寄件人姓名', 'required');
        $this->form_validation->set_rules('se_mobile', '寄件人手机', 'required');
        $this->form_validation->set_rules('se_state', '寄件人省份', 'required');
        $this->form_validation->set_rules('se_city', '寄件人城市', 'required');
        $this->form_validation->set_rules('se_address', '寄件人地址', 'required');
        $this->form_validation->set_rules('se_postcode', '寄件人邮编', 'required');

        $this->form_validation->set_rules('ordersn', '用户订单号', 'required');
        $this->form_validation->set_rules('weight', '用户重量', 'required');       

        if ($this->form_validation->run() == TRUE)
        {
            $sfdata=array(
                "orderid" => $this->input->post('orderid'),
                "enname" => $this->input->post('enname'),
                "cnname" => $this->input->post('cnname'),
                "ordersn" => $this->input->post('ordersn'),
                "number" => $this->input->post('number'),
                "price" => $this->input->post('price'),
                "total" => $this->input->post('total'),
                "reciver" => $this->input->post('reciver'),
                "addtime" => date("Y-m-d H:i:s"),
                "re_state" => $this->input->post('re_state'),
                "re_city" => $this->input->post('re_city'),
                "re_postcode" => $this->input->post('re_postcode'),
                "re_address" => $this->input->post('re_address'),
                "re_mobile" => $this->input->post('re_mobile'),
                "re_phone" => $this->input->post('re_phone'),
                "se_company" => $this->input->post('se_company'),
                "re_country" => $this->input->post('re_country'),
                "sender" => $this->input->post('sender'),
                "se_mobile" => $this->input->post('se_mobile'),
                "se_state" => $this->input->post('se_state'),
                "se_city" => $this->input->post('se_city'),
                "se_address" => $this->input->post('se_address'),
                "se_postcode" => $this->input->post('se_postcode'),
                "method" => $this->input->post('method'),
                "weight" => $this->input->post('weight'),
                "length" => $this->input->post('length'),
                "width" => $this->input->post('width'),
                "height" => $this->input->post('height'),                
                "adminid"=>$this->ion_auth->get_user_id()
            );

            if($sfdata["orderid"] && $sfdata["method"]=="F22")
            {
                $check=$this->sf_model->get_by_oid($sfdata["orderid"]);
                if($check)
                {
                    $this->session->set_flashdata('message', "该订单已有发货记录，请勿重复提交");
                    redirect('backend/sfexpress', 'refresh');
                    die();
                }
                $sfdata["sfordersn"]="";
                $this->sf_model->create($sfdata);
                $this->session->set_flashdata('message', "顺丰预约CD下单成功，请耐心等候");
                redirect('backend/sfexpress', 'refresh');
                die();

            }
            else
            {
                $this->load->library('libsfexpress',["apiid"=>$config["sfapiid"],"apikey"=>$config["sfapikey"]]);
                $sfresult=$this->libsfexpress->createsforder($sfdata);

                if($sfresult["status"]==0)
                {
                    $this->session->set_flashdata('message', $sfresult["msg"]);
                }
                else
                {
                    //$sfdata["pdfurl"]=$sfresult["pdf"];
                    $sfdata["sfordersn"]=$sfresult["id"];
                    $newsf=$this->sf_model->create($sfdata);
                    if($sfdata["orderid"]>0)
                    {
                        $order=$this->siteorder_model->getitembyid($sfdata["orderid"]);
                        if($order&&$order["siteid"]>0)
                        {
                            $site=$this->site_model->getitembyid($order["siteid"]);
                            if(!empty($site))
                            {

                                switch($site["sitetype"])
                                {
                                    case 1:
                                        $this->load->library('sitetype/prestashop',$site,'mysite');
                                        break;
                                    case 2:
                                        $extra=json_decode($site["extra"],true);
                                        $this->load->library('sitetype/shopify',$extra,'mysite');
                                        break;
                                    case 3:
                                        $extra=json_decode($site["extra"],true);
                                        $this->load->library('sitetype/bigcommerce',$extra,'mysite');
                                        break;							
                                }
                                if($this->mysite->checklink)
                                {
                                    /*
                                    $queryurl="http://www.sf-express.com/us/en/dynamic_function/waybill/#search/bill-number/".$sfresult["id"];
                                    $this->mysite->shiporder($order["apiid"],$sfresult["id"],$queryurl);
                                    */

                                    $newdata["shipping"]=$sfresult["id"];
                                    $newdata["state"]=4;
                                    $newdata["shipcount"]=$order["shipcount"]-1;
                                    
                                    $result = $this->mysite->shiporder($order["oid"],$sfresult["id"]);
                                    if($result=="ok")
                                    {
                                        $this->siteorder_model->update($order["id"], $newdata);
                                    }
                                }
                            }
                        }
                    }
                    /*
                    $pdf=$this->libsfexpress->URL($sfdata["ordersn"]);
                    if($pdf)
                    {
                        $newdata=["pdfurl"=>$pdf];
                        $this->sf_model->update($newsf["id"],$newdata);                    
                    }
                    */

                    $this->session->set_flashdata('message', "顺丰在线下单成功");
                    redirect('backend/sfexpress', 'refresh');
                    die();

                }

                
            }
            
        }
        $defordersn=$defprice=$defcnname=$defenname=$defname=$defaddress=$defzip=$defphone=$defprovince=$defcity="";
        if($orderid>0)
        {
            $order=$this->siteorder_model->getitembyid($orderid);
            if($order)
            {   
                $order["productinfo"]=json_decode($order["productinfo"],true);
                $this->data['order']= $order;
                $defname=$order["realname"];
                $defaddress=$order["address1"]." ".$order["address2"];
                $defzip=$order["zipcode"];
                $defphone=$order["phone"];
                $defprovince=$order["provineiso"];
                $defcity=$order["city"];
                $defenname=$order["productinfo"][0]["name"];
                $defordersn=$order["ordersn"];
                //$defprice=$order["total_price"];
                $defprice="10";
                
                $arrName = array(
                    'shoe' => array('en' => 'shoes', 'cn' => '鞋子'),
                    'glasse' => array('en' => 'glasses', 'cn' => '眼镜'),
                    'Wallet' => array('en' => 'Wallet', 'cn' => '钱包'),
                    'dress' => array('en' => 'Dress', 'cn' => '裙子'),
                    'Sleeve' => array('en' => 'Sleeves', 'cn' => 'T恤衫'),
                    'Shirt' => array('en' => 'Shirt', 'cn' => 'T恤衫'),
                    'Hoodie' => array('en' => 'Hoodie', 'cn' => '运动衫'),
                    'Jersey' => array('en' => 'Jersey', 'cn' => '运动衫'),
                    'Coat' => array('en' => 'Coat', 'cn' => '外套'),
                    'Jacket' => array('en' => 'Jacket', 'cn' => '外套'),
                    'Pant' => array('en' => 'Pant', 'cn' => '裤子'),
                    'Vest' => array('en' => 'Vest', 'cn' => '背心'),
                    'hat' => array('en' => 'Hat', 'cn' => '帽子'),
                    'bags' => array('en' => 'Bags', 'cn' => '包'),
                );

                foreach ( $arrName as $key => $arr ) {
                    if ( stripos($defenname, $key) === false )
                        continue;
                    $defenname = $arr['en'];
                    $defcnname = $arr['cn'];
                    break;
                }
            }

        }

        $this->data['orderid']= $orderid;        
        $this->data['ordersn'] = array(
            'name'  => 'ordersn',
            'id'    => 'ordersn',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('ordersn')?$this->form_validation->set_value('ordersn'):$defordersn,
        );

        $this->data['enname'] = array(
            'name'  => 'enname',
            'id'    => 'enname',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('enname')?$this->form_validation->set_value('enname'):$defenname,
        );
        $this->data['cnname'] = array(
            'name'  => 'cnname',
            'id'    => 'cnname',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('cnname')?$this->form_validation->set_value('cnname'):$defcnname,
        );

        $this->data['number'] = array(
            'name'  => 'number',
            'id'    => 'number',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('number')?$this->form_validation->set_value('number'):1,
        );
        $this->data['price'] = array(
            'name'  => 'price',
            'id'    => 'price',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('price')?$this->form_validation->set_value('price'):$defprice,
        );
        $this->data['total'] = array(
            'name'  => 'total',
            'id'    => 'total',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('total')?$this->form_validation->set_value('total'):$defprice,
        );

        $this->data['reciver'] = array(
            'name'  => 'reciver',
            'id'    => 'reciver',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('reciver')?$this->form_validation->set_value('reciver'):$defname,
        );


        $this->data['re_state'] = array(
            'name'  => 're_state',
            'id'    => 're_state',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_state')?$this->form_validation->set_value('re_state'):$defprovince,
        );
        $this->data['re_city'] = array(
            'name'  => 're_city',
            'id'    => 're_city',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_city')?$this->form_validation->set_value('re_city'):$defcity,
        );
        $this->data['re_address'] = array(
            'name'  => 're_address',
            'id'    => 're_address',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_address')?$this->form_validation->set_value('re_address'):$defaddress,
        );
        $this->data['re_phone'] = array(
            'name'  => 're_phone',
            'id'    => 're_phone',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_phone')?$this->form_validation->set_value('re_phone'):$defphone,
        );
        $this->data['re_mobile'] = array(
            'name'  => 're_mobile',
            'id'    => 're_mobile',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_mobile')?$this->form_validation->set_value('re_mobile'):$defphone,
        );
        $this->data['re_postcode'] = array(
            'name'  => 're_postcode',
            'id'    => 're_postcode',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('re_postcode')?$this->form_validation->set_value('re_postcode'):$defzip,
        );

       

        $this->data['sender'] = array(
            'name'  => 'sender',
            'id'    => 'sender',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('sender')?$this->form_validation->set_value('sender'):$config["defsendername"],
        );

        $this->data['se_company'] = array(
            'name'  => 'se_company',
            'id'    => 'se_company',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_company')?$this->form_validation->set_value('se_company'):$config["defsendercom"],
        );

        $this->data['se_state'] = array(
            'name'  => 'se_state',
            'id'    => 'se_state',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_state')?$this->form_validation->set_value('se_state'):$config["defsenderprovince"],
        );

        $this->data['se_city'] = array(
            'name'  => 'se_city',
            'id'    => 'se_city',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_city')?$this->form_validation->set_value('se_city'):$config["defsendercity"],
        );

        $this->data['se_address'] = array(
            'name'  => 'se_address',
            'id'    => 'se_address',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_address')?$this->form_validation->set_value('se_address'):$config["defsenderaddress"],
        );
        $this->data['se_postcode'] = array(
            'name'  => 'se_postcode',
            'id'    => 'se_postcode',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_postcode')?$this->form_validation->set_value('se_postcode'):$config["defsenderpost"],
        );
        $this->data['se_mobile'] = array(
            'name'  => 'se_mobile',
            'id'    => 'se_mobile',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('se_mobile')?$this->form_validation->set_value('se_mobile'):$config["defsenderphone"],
        );
        
        $this->data['length'] = array(
            'name'  => 'length',
            'id'    => 'length',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('length'),
        );
        $this->data['height'] = array(
            'name'  => 'height',
            'id'    => 'height',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('height'),
        );
        $this->data['width'] = array(
            'name'  => 'width',
            'id'    => 'width',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('width'),
        );
        
        $this->data['weight'] = array(
            'name'  => 'weight',
            'id'    => 'weight',
            'type'  => 'text',
            'class' => 'form-control',
            'value' => $this->form_validation->set_value('weight')?$this->form_validation->set_value('weight'):"0.1",
        );


		
		//
		$this->data['content_header_title'] = content_header_title($this->data['page_title'],'顺丰物流');
        $this->data['content'] = 'sfexpress/post';
        
        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));

		//
		$this->render();
    }
    
    public function pdf($id)
    {

        $newsf=$this->sf_model->getitembyid($id);
        
        $config = $this->systemconfig_model->get_configs(); 
        $this->load->library('libsfexpress',["apiid"=>$config["sfapiid"],"apikey"=>$config["sfapikey"]]);        
        $pdf=$this->libsfexpress->URL($newsf["ordersn"]);
        if($pdf)
        {
            $newdata=["pdfurl"=>$pdf];
            $this->sf_model->update($newsf["id"],$newdata);  
            redirect($pdf);                  
            //echo "<a href='".$pdf."'>".$pdf."</a>";
            //die();
        }
        else
        {
            echo "refresh page";
            die();
        }
    }

    public function ajaxdel()
    {

        $return=["status"=>1];
		$cid=$this->input->post("cid");
        if(!$this->sf_model->delitem($cid))
        {
            $return["status"]=0;
            $return["msg"]="删除失败";
        }       
        echo json_encode($return);
        die();
    }

    public function record()
	{
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			$this->data['page_title'] => 'backend/sfexpress'
		);

		$page=max(1,(int) $this->input->get('page'));
        $key=trim($this->input->get('keyword'));
        $adminid=(int) $this->input->get('adminid');
        
        $page_data=$this->sf_model->getpage($page,$key);
        $this->data['data']=$page_data["data"];
        $this->data['pager']=$page_data["pager"];

        $this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
        $this->data['page']=$page;      

        
        $keyword = array(
                'name'      => 'keyword',
                'id'        => 'keyword',
                'value'     =>  $key,
                'class'     =>  'form-control input-sm',
                'placeholder'=> '请输入关键字',
                'maxlength' => '100'
        );
		$this->data['keyword']=$keyword;
		
		//
		$this->data['content_header_title'] = content_header_title($this->data['page_title']," 列表");
		$this->data['content'] = 'sfexpress/record';

		//
		$this->render();
    }
    

}
